<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input
          v-model="queryParams.roleCode"
          placeholder="请输入角色编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色级别" prop="roleLevel">
        <el-select v-model="queryParams.roleLevel" placeholder="请选择角色级别" clearable>
          <el-option
            v-for="dict in pm_role_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in pm_role_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="small"
          @click="handleAdd"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Plus /></el-icon>新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Edit /></el-icon>修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="角色编码" align="center" prop="roleCode" />
      <el-table-column label="角色级别" align="center" prop="roleLevel">
        <template #default="scope">
          <dict-tag 
            :options="pm_role_level || []" 
            :value="scope.row.roleLevel"
            v-if="pm_role_level && pm_role_level.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.roleLevel || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否系统角色" align="center" prop="isSystem">
        <template #default="scope">
          <dict-tag 
            :options="pm_role_system || []" 
            :value="scope.row.isSystem"
            v-if="pm_role_system && pm_role_system.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.isSystem || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag 
            :options="pm_role_status || []" 
            :value="scope.row.status"
            v-if="pm_role_status && pm_role_status.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.status || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click="handlePermission(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Setting /></el-icon>权限
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团队角色对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="角色级别" prop="roleLevel">
          <el-select v-model="form.roleLevel" placeholder="请选择角色级别">
            <el-option
              v-for="dict in pm_role_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否系统角色" prop="isSystem">
          <el-radio-group v-model="form.isSystem">
            <el-radio
              v-for="dict in pm_role_system"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in pm_role_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 角色权限配置对话框 -->
    <el-dialog title="角色权限配置" v-model="permissionOpen" width="600px" append-to-body>
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="{ children: 'children', label: 'permissionName' }"
        node-key="permissionId"
        show-checkbox
        check-strictly
        default-expand-all
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPermission">确 定</el-button>
          <el-button @click="permissionOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { listTeamRole, getTeamRole, delTeamRole, addTeamRole, updateTeamRole, assignRolePermissions, getRolePermissions, getPermissionTree } from "@/api/pm/team";
import { Search, Refresh, Plus, Edit, Delete, Setting } from '@element-plus/icons-vue';
import RightToolbar from '@/components/RightToolbar/index.vue';
import DictTag from '@/components/DictTag/index.vue';
import Pagination from '@/components/Pagination/index.vue';

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 获取字典数据
const { pm_role_level, pm_role_status, pm_role_system } = toRefs<any>(proxy?.useDict('pm_role_level', 'pm_role_status', 'pm_role_system'))

// 表单引用
const formRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()
const permissionTreeRef = ref()

// 响应式数据
const loading = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const roleList = ref<any[]>([])
const permissionTree = ref<any[]>([])
const title = ref("")
const open = ref(false)
const permissionOpen = ref(false)
const currentRoleId = ref<number>()
const pendingPermissionIds = ref<number[]>([])

// 查询参数
const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  roleName: null,
  roleCode: null,
  roleLevel: null,
  status: null,
})

// 表单参数
const form = ref<any>({
  roleId: null,
  roleName: null,
  roleCode: null,
  description: null,
  roleLevel: 1,
  isSystem: "0",
  sortOrder: 0,
  status: "0",
  remark: null
})

// 表单校验
const rules = reactive({
  roleName: [
    { required: true, message: "角色名称不能为空", trigger: "blur" }
  ],
  roleCode: [
    { required: true, message: "角色编码不能为空", trigger: "blur" }
  ],
  roleLevel: [
    { required: true, message: "角色级别不能为空", trigger: "change" }
  ]
})

// 监听权限树数据变化，自动设置选中状态
watch(permissionTree, (newTree) => {
  if (newTree && newTree.length > 0 && pendingPermissionIds.value.length > 0) {
    proxy?.$nextTick(() => {
      if (permissionTreeRef.value) {
        permissionTreeRef.value.setCheckedKeys(pendingPermissionIds.value);
        pendingPermissionIds.value = []; // 清空待设置的权限ID
      }
    });
  }
}, { deep: true });

// 生命周期
onMounted(() => {
  getList()
  getPermissionTreeData()
})

// 方法定义
/** 查询团队角色列表 */
const getList = () => {
  loading.value = true;
  listTeamRole(queryParams).then(response => {
    roleList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取角色列表失败:', error);
    roleList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 获取权限树数据 */
const getPermissionTreeData = () => {
  return getPermissionTree().then(response => {
    permissionTree.value = response.data || [];
    return response.data || [];
  }).catch(error => {
    console.error('获取权限树失败:', error);
    permissionTree.value = [];
    return [];
  });
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}

// 表单重置
const reset = () => {
  form.value = {
    roleId: null,
    roleName: null,
    roleCode: null,
    description: null,
    roleLevel: 1,
    isSystem: "0",
    sortOrder: 0,
    status: "0",
    remark: null
  };
  proxy?.$nextTick(() => {
    formRef.value?.resetFields();
  });
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  proxy?.$nextTick(() => {
    queryFormRef.value?.resetFields();
  });
  handleQuery();
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.roleId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加团队角色";
}

/** 修改按钮操作 */
const handleUpdate = (row?: any) => {
  reset();
  const roleId = row?.roleId || ids.value[0]
  getTeamRole(roleId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改团队角色";
  });
}

/** 权限配置按钮操作 */
const handlePermission = async (row: any) => {
  currentRoleId.value = row.roleId;
  
  // 获取角色权限
  const response = await getRolePermissions(row.roleId);
  const permissionIds = response.data || [];
  
  // 如果权限树数据已加载，直接设置选中状态
  if (permissionTree.value && permissionTree.value.length > 0) {
    permissionOpen.value = true;
    proxy?.$nextTick(() => {
      if (permissionTreeRef.value) {
        permissionTreeRef.value.setCheckedKeys(permissionIds);
      }
    });
  } else {
    // 如果权限树数据未加载，先存储待设置的权限ID，然后加载数据
    pendingPermissionIds.value = permissionIds;
    await getPermissionTreeData();
    permissionOpen.value = true;
  }
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.roleId != null) {
        updateTeamRole(form.value).then(response => {
          proxy?.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTeamRole(form.value).then(response => {
          proxy?.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交权限配置 */
const submitPermission = () => {
  const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
  // 确保权限ID以字符串形式传递，避免JavaScript精度问题
  const permissionIds = checkedKeys.map(id => String(id));
  assignRolePermissions(currentRoleId.value!, permissionIds).then(response => {
    proxy?.$modal.msgSuccess("权限配置成功");
    permissionOpen.value = false;
  });
}

/** 删除按钮操作 */
const handleDelete = (row?: any) => {
  const roleIds = row?.roleId ? [row.roleId] : ids.value
  proxy?.$modal.confirm('是否确认删除团队角色编号为"' + roleIds.join(',') + '"的数据项？').then(function() {
    return delTeamRole(roleIds);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
</script>
